package com.zxh.blog.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.zxh.blog.R
import com.zxh.blog.activity.ArticleDetailActivity
import com.zxh.blog.adapter.ArticleRecyclerAdapter
import com.zxh.blog.bean.Article
import com.zxh.blog.bean.PageArticle
import com.zxh.blog.bean.ResponseJson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class ArticleListFragment : Fragment() {

    private lateinit var mRecyclerView: RecyclerView

    private lateinit var mAdapter: ArticleRecyclerAdapter

    private var mArticleList = ArrayList<Article>()

    private val mBaseURL =
        "http://43.140.201.43:7777/article/articleList?pageNum=1&pageSize=5&categoryId="

    private var mRefreshFlag = false

    private var mPageNum = 1

    @SuppressLint("MissingInflatedId")
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.d("ArticleListFragment", "onCreateView: 分类文章列表")
        val view = inflater.inflate(R.layout.fragment_article, container, false)
        // 获取传递给Fragment的参数值
        val categoryId = arguments?.getString("category_id")
        // 调用后端接口接收并解析json数据
        val url = mBaseURL + categoryId
        initDataByOkhttp(url)
        // 初始化RecyclerView
        mRecyclerView = view.findViewById(R.id.articleList)
        // 初始化适配器
        mAdapter = ArticleRecyclerAdapter(requireContext())

        return view
    }

    override fun onStart() {
        super.onStart()
        // 设置item点击事件
        mAdapter.setClickListener(object : ArticleRecyclerAdapter.ClickListener {
            override fun onClick(position: Int, articleList: ArrayList<Article>) {
                val article = articleList[position]
                val id = article.id
                // 跳转到文章详情页面
                jumpToArticleDetailWebView(id)
            }
        })
    }

    /**
     *  根据文章id调转到对应的文章详情页面
     */
    private fun jumpToArticleDetailWebView(id: String) {
        val intent = Intent(requireContext(), ArticleDetailActivity::class.java)
        intent.putExtra("articleId", id)
        startActivity(intent)
    }

    private fun initDataByOkhttp(url: String) {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(url)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val responseData = response.body?.string()
                if (responseData != null) {
                    parseJSONWithGSON(responseData)
                    // 将UI更新操作移动到主线程
                    Handler(Looper.getMainLooper()).post {
                        // 更新UI视图
                        updateUI()
                    }
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }

    private fun updateUI() {
        // 在这里更新UI视图
        // 设置布局和适配器
        val layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        mRecyclerView.layoutManager = layoutManager
        mRecyclerView.adapter = mAdapter
        mAdapter.setData(mArticleList)
    }

    private fun parseJSONWithGSON(responseData: String) {
        val gson = Gson()
        val typeToken = object : TypeToken<ResponseJson<PageArticle<Article>>>() {}.type
        val data: ResponseJson<PageArticle<Article>> = gson.fromJson(responseData, typeToken)
        mArticleList = data.data?.rows as ArrayList<Article>
        // 创建一个临时的文章列表，用于存储截取summary后的Article对象
        val articleList = ArrayList<Article>()
        for (article in mArticleList) {
            // 限制summary（文章摘要）的字符长度为20
            if (article.summary.length > 40) {
                article.summary = article.summary.substring(0, 40) + "..."
            }
            articleList.add(article)
        }
        mArticleList = articleList
    }

    companion object {
        fun newInstance(categoryId: String): ArticleListFragment {
            val fragment = ArticleListFragment()
            val args = Bundle()
            args.putString("category_id", categoryId)
            fragment.arguments = args
            return fragment
        }
    }
}